package com.ls.lserp.modules.material.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ls.lserp.common.utils.CollectionsUtils;
import com.ls.lserp.dbaccess.Entity.SampleEntity;
import com.ls.lserp.dbaccess.Entity.SampleSizeQuantityEntity;
import com.ls.lserp.modules.sys.utils.SystemMessageUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ls.lserp.common.config.Global;
import com.ls.lserp.common.persistence.AjaxDone;
import com.ls.lserp.common.persistence.BaseEntity;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.StringUtils;
import com.ls.lserp.common.web.BaseController;
import com.ls.lserp.modules.common.entity.OgnizationEntity;
import com.ls.lserp.modules.material.entity.SlopworkOutrequest;
import com.ls.lserp.modules.material.service.SlopworkOutrequestService;
import com.ls.lserp.modules.sys.utils.SequenceUtil;

import freemarker.template.Configuration;
import groovy.util.ResourceException;

@Controller
@RequestMapping(value = "${adminPath}/slopwork/outrequest/")
public class SlopworkOutrequestController extends BaseController {
	
	// 保存 编辑 删除 方法
		@Autowired
		private SlopworkOutrequestService slopworkOutrequestService;		
		@Autowired
		Configuration freemarkerConfiguration;
		
		@ModelAttribute
		public SlopworkOutrequest get(@RequestParam(required = false) String id) {

			// 判断id是否为空
			if (StringUtils.isNotBlank(id)) {
				// 执行查询语句 查询基本信息
				return slopworkOutrequestService.get(Long.parseLong(id));
			} else {
				// 若为空，实例化
				return new SlopworkOutrequest();
			}
		}
		
		/**
		 * @Title: 画面跳转用
		 * @return url
		 */
		@RequiresPermissions("slopwork:outrequest:view")
		@RequestMapping(value = { "" })
		public String list(Model model) {
			// 画面跳转
			return "modules/material/SlopworkOutrequest";
		}

		/**
		 * @Title: 画面检索
		 * @Description: 查询页面
		 * @param slopworkOutrequest
		 * @param request
		 * @param response
		 * @param model
		 * @return searchList
		 * @throws Exception
		 */
		@RequiresPermissions("slopwork:outrequest:view")
		@RequestMapping(value = { "searchList" })
		@ResponseBody
		public String searchList(SlopworkOutrequest slopworkOutrequest, HttpServletRequest request, HttpServletResponse response,
				Model model) throws Exception {
			Map<Object, Object> listMap = new HashMap<Object, Object>();
			// ajax回调时使用的一览list名
			request.setAttribute(Global.LIST_NAME, "slopworkOutrequest");
			// 拼接字符串供分页使用
			StringBuilder searchParam = new StringBuilder();
			// 出库单号
			searchParam.append("&outboundRequestNo=");
			searchParam.append(slopworkOutrequest.getOutboundRequestNo());
			// 合同订单号
			searchParam.append("&customerContractNo=");
			searchParam.append(slopworkOutrequest.getCustomerContractNo());
			// 客户名称
			searchParam.append("&ocustomerName=");
			searchParam.append(slopworkOutrequest.getOcustomerName());
			// 日期
			searchParam.append("&dateFrom=");
			searchParam.append(slopworkOutrequest.getDateFrom());
			searchParam.append("&dateTo=");
			searchParam.append(slopworkOutrequest.getDateTo());
			// 状态
			searchParam.append("&tabPageStatus=");
			searchParam.append(slopworkOutrequest.getTabPageStatus());
			// 放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
			request.setAttribute(Global.SEARCH_PAEAM, searchParam.toString());
			
			// 查询一览页面数据
			Page<SlopworkOutrequest> page = slopworkOutrequestService.findList(new Page<SlopworkOutrequest>(request, response),slopworkOutrequest);
			// 读取系统路径
			String strUri = request.getContextPath() + Global.getAdminPath();
			// 读取文件生成字符串
			String strHtml = "";
			Map<String, Object> map = new HashedMap();
			map.put("adminUri", strUri);
			map.put("slopworkOutrequests", page.getList());
			map.put("pageNo", page.getPageNo());
			map.put("pageSize", page.getPageSize());
			strHtml = FreeMarkerTemplateUtils.processTemplateIntoString(freemarkerConfiguration.getTemplate("slopworkOutrequest.ftl"), map);
			listMap.put("slopworkOutrequest", strHtml);
			listMap.put("page", page.getHtml());

			// ajax返回结果
			return renderString(response, listMap);
		}
		
		/**
		    * 进入查看页面
		    * @param slopworkOutrequest
		    * @param model
		    * @return
		    */
		   @RequiresPermissions("slopwork:outrequest:view")
		   @RequestMapping(value = "show")
		   public String show(SlopworkOutrequest slopworkOutrequest, Model model) {
			   
		   	   // 查找入库申请明细
			   List<SlopworkOutrequest> resultRequestList = slopworkOutrequestService.findShowRequestDetailList(slopworkOutrequest);
			   slopworkOutrequest.setRequestOutDetailsList(resultRequestList);
		   	
		       // 将查询结果赋值mvc model层返回jsp页面
		       model.addAttribute("slopworkOutrequest", slopworkOutrequest);
		       
		       // 返回页面地址
		       return "modules/material/slopworkOutrequestShow";
		   }
		   
		   /**
			 * 进入编辑页面
			 * @param slopworkOutrequest
			 * @param model
			 * @return
			 */
			@RequiresPermissions("slopwork:outrequest:edit")
			@RequestMapping(value = "form")
			public String form(SlopworkOutrequest slopworkOutrequest,Model model) {
				
				// 合同编号
				List<SlopworkOutrequest> resultContractLis = slopworkOutrequestService.getContractList();
				slopworkOutrequest.setContractList(resultContractLis);
				
				// 样品需求
				List<SampleEntity> resultSamplyOrderList = slopworkOutrequestService.getSamplyOrderList();
				slopworkOutrequest.setSamplyOrderList(resultSamplyOrderList);
				// 创建
				if(slopworkOutrequest.getId() == null){
					// 入库单条码
					slopworkOutrequest.setOstockBarCode(SequenceUtil.outslopworkRequestbarcode().getReturnCode());
				// 编辑
				}else{
					// 出库申请类别,样品成衣出库
					if(slopworkOutrequest.getOutboundCategory().equals(ResourcesUtil.getConfig("clothes_out_category_Samply"))){
						// 下拉款式
						List<SlopworkOutrequest> styleList = new ArrayList<SlopworkOutrequest>();
						SlopworkOutrequest sl = new SlopworkOutrequest();
			    		sl.setStyleId(slopworkOutrequest.getStyleId());
			    		sl.setOcustomerStyleNo(slopworkOutrequest.getOcustomerStyleNo());
			    		styleList.add(sl);
			    		slopworkOutrequest.setOstyleList(styleList);
						List<SampleEntity> samplyOrderList = new ArrayList<SampleEntity>();
						SampleEntity samplyOrder = new SampleEntity();
						samplyOrder.setSampleRequestId(slopworkOutrequest.getSampleRequestId());
						samplyOrder.setSampleRequestNo(slopworkOutrequest.getCustomerContractNo());
						samplyOrderList.add(samplyOrder);
						slopworkOutrequest.setSamplyOrderList(samplyOrderList);
			    	// 出库申请类别,外发生产	
					}else if(slopworkOutrequest.getOutboundCategory().equals(ResourcesUtil.getConfig("clothes_out_category_order"))){
						// 订单成衣出库
						SlopworkOutrequest pSlopworkOutrequest = new SlopworkOutrequest();
						 List<SlopworkOutrequest> contractList  = new ArrayList<>();
						pSlopworkOutrequest.setContractId(slopworkOutrequest.getContractId());
						pSlopworkOutrequest.setContractNo(slopworkOutrequest.getContractNo());
						contractList.add(pSlopworkOutrequest);
						slopworkOutrequest.setContractList(contractList);
				    	// 下拉款式
						List<SlopworkOutrequest> styleList = new ArrayList<SlopworkOutrequest>();
						SlopworkOutrequest sl = new SlopworkOutrequest();
						sl.setStyleId(slopworkOutrequest.getStyleId());
						sl.setOcustomerStyleNo(slopworkOutrequest.getOcustomerStyleNo());
						styleList.add(sl);
						slopworkOutrequest.setOstyleList(styleList);
					}
					
				   	// 查找入库申请明细
					List<SlopworkOutrequest> resultRequestList = slopworkOutrequestService.findShowRequestDetailList(slopworkOutrequest);
					slopworkOutrequest.setRequestOutDetailsList(resultRequestList);
				}
				
				// 将实体类值赋给mvc model层返回jsp页面
				model.addAttribute("slopworkOutrequest", slopworkOutrequest);
				
				// 返回页面地址
				return "modules/material/SlopworkOutrequestCreate";
			}
			
			 /**
			    * @Title: delRequestDetail
			    * @Description: 删除出库申请明细
			    * @param @param inventoryRequest
			    * @param @param model
			    * @param @param session
			    * @param @return
			    * @return String 
			    * @throws
			    */

			  @RequiresPermissions("slopwork:outrequest:edit")
			  @RequestMapping(value = "delAllDetails")
			  public String delAllDetails(SlopworkOutrequest slopworkOutrequest, Model model) {
			      try {
			    	  
			    	  slopworkOutrequest.setRequestOutDetailsList(new ArrayList<SlopworkOutrequest>());
			   	   
			  	       // 将page值赋值给mvc model层返回jsp页面
			     	   model.addAttribute("slopworkOutrequest", slopworkOutrequest);
			  	    
			         // 返回地址
			         return "modules/material/SlopworkOutrequestCreate";
			      } catch (Exception e) {
			          // 记录日志
			          logger.error(e.getMessage(), e);
			          // 返回地址
			          return "modules/material/SlopworkOutrequestCreate";
			      }
			  }
			  
			  /**
			     * @Title: findStyle
			     * @Description: 合同编号联动
			     * @param @param oproductionId
			     * @param @param session
			     * @param @return
			     * @return String 
			     * @throws
			     */
			   
			   @RequiresPermissions("slopwork:outrequest:edit")
			   @RequestMapping(value = "selContract")
			   public String selProduction(Long contractId, HttpServletRequest request, HttpServletResponse response, Model model) {
			       try {
			    	   SlopworkOutrequest pSlopworkOutrequest = new SlopworkOutrequest();
					   pSlopworkOutrequest.setContractId(contractId);
					   List<SlopworkOutrequest> resultStyleList =slopworkOutrequestService.getContractStyleList(pSlopworkOutrequest);
					   pSlopworkOutrequest.setOstyleList(resultStyleList);
/*			    	   SlopworkOutrequest slopworkInfo = slopworkOutrequestService.getProduction(pSlopworkOutrequest);
				    	
				    	if(slopworkInfo != null){
				    		slopworkInfo.setOutboundRequestNo("OUT" + slopworkInfo.getStyleNo());
				    		List<SlopworkOutrequest> styleList = new ArrayList<SlopworkOutrequest>();
				    		SlopworkOutrequest sl = new SlopworkOutrequest();
				    		sl.setStyleId(slopworkInfo.getStyleId());
				    		sl.setOcustomerStyleNo(slopworkInfo.getOcustomerStyleNo());
				    		styleList.add(sl);
				    		slopworkInfo.setOstyleList(styleList);
				    		pSlopworkOutrequest = new SlopworkOutrequest();
				    		pSlopworkOutrequest.setContractId(slopworkInfo.getContractId());
				    		pSlopworkOutrequest.setIndentId(slopworkInfo.getIndentId());
				    		pSlopworkOutrequest.setStyleId(slopworkInfo.getStyleId());
				    		slopworkInfo.setRequestOutDetailsList(slopworkOutrequestService.findCreateRequestDetailList(pSlopworkOutrequest));
				    	}*/
				   	    // 将page值赋值给mvc model层返回jsp页面
				   	    model.addAttribute("slopworkOutrequest", pSlopworkOutrequest);
			   	    
			           // 返回地址
			           return "modules/material/SlopworkOutrequestCreate";
			       } catch (Exception e) {
			           // 记录日志
			           logger.error(e.getMessage(), e);
			           // 返回地址
			           return "modules/material/SlopworkOutrequestCreate";
			       }
			   }
			  
			  /**
			     * @Title: findStyle
			     * @Description: 生产制单联动
			     * @param @param oproductionId
			     * @param @param session
			     * @param @return
			     * @return String 
			     * @throws
			     */
			   
			   @RequiresPermissions("slopwork:outrequest:edit")
			   @RequestMapping(value = "selFabricat")
			   public String selFabricat(Long ofabricatId, HttpServletRequest request, HttpServletResponse response, Model model) {
			       try {
			    	   SlopworkOutrequest pSlopworkOutrequest = new SlopworkOutrequest();
			    	   pSlopworkOutrequest.setOfabricatId(ofabricatId);
				    	List<SlopworkOutrequest> slopworkList = slopworkOutrequestService.getContractProcessingList(pSlopworkOutrequest);
				    	
				    	SlopworkOutrequest resultSlop = new SlopworkOutrequest();
				    	resultSlop.setOcontractProcessList(slopworkList);
				    	
				   	    // 将page值赋值给mvc model层返回jsp页面
				   	    model.addAttribute("slopworkOutrequest", resultSlop);
			   	    
			           // 返回地址
			           return "modules/material/SlopworkOutrequestCreate";
			       } catch (Exception e) {
			           // 记录日志
			           logger.error(e.getMessage(), e);
			           // 返回地址
			           return "modules/material/SlopworkOutrequestCreate";
			       }
			   }
			   
			   /**
			     * @Title: findStyle
			     * @Description: 样品需求联动
			     * @param @param oproductionId
			     * @param @param session
			     * @param @return
			     * @return String 
			     * @throws
			     */
			   
			   @RequiresPermissions("slopwork:outrequest:edit")
			   @RequestMapping(value = "selContractProcess")
			   public String selContractProcess(Long sampleRequestId, HttpServletRequest request, HttpServletResponse response, Model model) {
			       try {
			    	   SlopworkOutrequest pSlopworkOutrequest = new SlopworkOutrequest();
			    	   pSlopworkOutrequest.setSampleRequestId(sampleRequestId);
				    	List<SlopworkOutrequest> slopworkList = slopworkOutrequestService.getStyleList(pSlopworkOutrequest);
					   if(!CollectionsUtils.isEmpty(slopworkList) ){
						   pSlopworkOutrequest.setOutboundRequestNo("OUT" + slopworkList.get(0).getStyleNo());
						   pSlopworkOutrequest.setStyleId(slopworkList.get(0).getStyleId());
						   pSlopworkOutrequest.setOcustomerStyleNo(slopworkList.get(0).getOcustomerStyleNo());
						   pSlopworkOutrequest.setOstyleList(slopworkList);
						   List<SlopworkOutrequest> sampleSizeQuantityEntityList = slopworkOutrequestService.findCreateSamplyRequestDetailList(pSlopworkOutrequest);
                           pSlopworkOutrequest.setRequestOutDetailsList(sampleSizeQuantityEntityList);
					   }
				   	    // 将page值赋值给mvc model层返回jsp页面
				   	    model.addAttribute("slopworkOutrequest", pSlopworkOutrequest);
			   	    
			           // 返回地址
			           return "modules/material/SlopworkOutrequestCreate";
			       } catch (Exception e) {
			           // 记录日志
			           logger.error(e.getMessage(), e);
			           // 返回地址
			           return "modules/material/SlopworkOutrequestCreate";
			       }
			   }
			   
			   /**
			     * @Title: selStyle
			     * @Description: 选择款
			     * @param @param oproductionId
			     * @param @param session
			     * @param @return
			     * @return String 
			     * @throws
			     */
			   
			   @RequiresPermissions("slopwork:outrequest:edit")
			   @RequestMapping(value = "selStyle")
			   public String selStyle(String styleNo,Long styleId, HttpServletRequest request, HttpServletResponse response, Model model) {
			       try {

					   SlopworkOutrequest slopworkInfo = new SlopworkOutrequest();
				    	// 设置入库单号"IN"+款号
				    	if(!"".equals(styleId) ){
							List<SlopworkOutrequest> styleList = slopworkOutrequestService.getStyleNoByStyleId(styleId);
				    		slopworkInfo.setOutboundRequestNo("OUT"+ styleList.get(0).getStyleNo());
							//款式ID
							slopworkInfo.setStyleId(styleId);
							//外发加工合同ID
							slopworkInfo.setOcontractProcessId(styleList.get(0).getOcontractProcessId());
							//生产制单ID
							slopworkInfo.setOproductionId(styleList.get(0).getOproductionId());
							//合同订单ID
							slopworkInfo.setIndentId(styleList.get(0).getIndentId());
							List<SlopworkOutrequest> slopworkInforResult = slopworkOutrequestService.findCreateContractList(slopworkInfo);
							slopworkInfo.setRequestOutDetailsList(slopworkInforResult);

				    	}
				    	
				   	    // 将page值赋值给mvc model层返回jsp页面
				   	    model.addAttribute("slopworkOutrequest", slopworkInfo);
			   	    
			           // 返回地址
			           return "modules/material/SlopworkOutrequestCreate";
			       } catch (Exception e) {
			           // 记录日志
			           logger.error(e.getMessage(), e);
			           // 返回地址
			           return "modules/material/SlopworkOutrequestCreate";
			       }
			   }
			   
			   /**
			    * 保存信息
			    * @param slopworkOutrequest
			    * @param response
			    * @return
			    * @throws ResourceException 
			    */
			   @RequiresPermissions("slopwork:outrequest:edit")
			   @RequestMapping(value = "save")
			   @ResponseBody
			   public String save(SlopworkOutrequest slopworkOutrequest, HttpServletResponse response ) throws ResourceException {

					// 判断id是否为null （判断新建或修改）
					if(slopworkOutrequest.getId()!=null){
						// 编辑数据
						// 判断数据是否删除
						SlopworkOutrequest inventoryRequestNew = get(slopworkOutrequest.getId().toString());
						// 判断数据是否删除
			           if(inventoryRequestNew==null || BaseEntity.DEL_FLAG_DELETE.equals(inventoryRequestNew.getDeleteFlag())){
			           	// 返回提示信息
			           	return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
			           }
						
			           // 排他处理
					    if(slopworkOutrequest.getVersion()==get(slopworkOutrequest.getId().toString()).getVersion()){
					    	
					    	// 版本号加1
					    	slopworkOutrequest.setVersion(slopworkOutrequest.getVersion()+1);
					    }else{
					    	
					    	// 返回提示信息
					        return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
					    }
					    
					    // 入库申请类别,生产制单 
						if(slopworkOutrequest.getOutboundCategory().equals(ResourcesUtil.getConfig("clothes_out_category_production"))){
							// 清空外发合同订单id
							slopworkOutrequest.setOcontractProcessId(null);
				    	// 入库申请类别,外发生产	
						}else if(slopworkOutrequest.getOutboundCategory().equals(ResourcesUtil.getConfig("clothes_out_category_processing"))){
							// 清空生产制单id
							slopworkOutrequest.setOproductionId(null);
						}
					}
				   
			   	   // 保存入库申请
					slopworkOutrequestService.saveInventoryRequest(slopworkOutrequest);
			   	
			   	   // 保存成功返回提示信息
			       return renderString(response,AjaxDone.ok(SystemMessageUtils.getMessageName( "inventory_request_save_success")));
			   }
}
